﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PasswordManager
{
   class DataSaveLoadInterface
   {
      protected string m_strLastFile;

      public DataSaveLoadInterface()
      {
         m_strLastFile = "";
      }

      public string GetLastFile()
      {
         return m_strLastFile;
      }

      public void ClearLastFile()
      {
         m_strLastFile = "";
      }

      public bool LoadFromFile(string strPathAndFileName, KeyPairGroupList sList)
      {
         bool bRet = (System.IO.File.Exists(strPathAndFileName) == true);
         if (bRet == true)
         {
            System.IO.Stream sFile = new System.IO.FileStream(strPathAndFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
            System.Runtime.Serialization.IFormatter sFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            object sTmp = sFormatter.Deserialize(sFile);
            sList = sTmp as KeyPairGroupList;
            bRet = (sList != null);
            sFile.Close();
            m_strLastFile = strPathAndFileName;
         }
         return bRet;
      }

      public bool SaveToFile(string strPathAndFileName, bool bOverwrite, KeyPairGroupList sList)
      {
         bool bRet = (sList != null);
         if (bRet == true)
         {
            if ((System.IO.File.Exists(strPathAndFileName) == true) && (bOverwrite == false))
            {
               bRet = false;
            }
         }
         if (bRet == true)
         {
            System.IO.Stream sFile = new System.IO.FileStream(strPathAndFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
            System.Runtime.Serialization.IFormatter sFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            sFormatter.Serialize(sFile, sList);
            sFile.Close();
            m_strLastFile = strPathAndFileName;
         }
         return bRet;
      }
   }
}
